
import React, { useEffect, useState, useMemo, useRef } from "react";
import { message, Space } from "antd";
import { v4 as uuidv4 } from "uuid";
import axios from "axios";
import {
  useXAgent,
  useXChat,
  XRequest
} from "@ant-design/x";
import AttachmentInput from "../components/AttachmentInput/AttachmentInput.js";
import BubbleChat from "../components/BubbleChat/BubbleChat.jsx";
import WelcomeMessage from "../components/WelcomeMessage/WelcomeMessage.js";
import TipsPrompts from "../components/TipsPrompts/TipsPrompts.js";
import ConversationsManger from "../components/ConversationsManger/ConversationsManger.js";
import ContentRenderer from "../utils/ContentRenderer.jsx";
import { getToken } from "../utils/auth.js";
import useStyle from "../views/Index/index";

// 渲染Markdown内容的函数
const RenderMarkdown = (content) => <ContentRenderer content={content} />;

// 定义API的基础URL和路径
const BASE_URL = process.env.REACT_APP_API_BASE_URL;
const PATH = process.env.REACT_APP_API_PATH;

const DefaultLayout = () => {
  const { styles } = useStyle();
  const [content, setContent] = useState("");
  const [conversationsItems, setConversationsItems] = useState([]);
  const [activeKey, setActiveKey] = useState("init");
  const [loading, setLoading] = useState(false);
  const [historyMessages, setHistoryMessages] = useState([]);
  const [conversationId, setConversationId] = useState(null);
  const [selectedModel, setSelectedModel] = useState("qwen2.5-72b-instruct");
  const abortRef = useRef(null);

  // 初始化XAgent
  const [agent] = useXAgent({ baseURL: `${BASE_URL}${PATH}` });

  // 使用XChat钩子
  const { messages, setMessages } = useXChat({
    agent,
    requestPlaceholder: "等待中...",
    requestFallback: "忙碌中，请重试",
  });

  const messagesItems = useMemo(
    () =>
      messages.map(({ id, message, role }) => {
        return {
          key: id,
          loading: message === "等待中..." ? true : false,
          role: role === "user" ? "user" : "assistant",
          content: message,
        };
      }),
    [messages]
  );

  // 统一的API请求函数
  const fetchApi = async (endpoint, options = {}) => {
    try {
      const response = await axios.get(`${BASE_URL}${PATH}${endpoint}`, {
        headers: {
          Authorization: `Bearer ${getToken()}`
        },
        ...options
      });
      return response.data;
    } catch (error) {
      handleApiError(error);
      throw error;
    }
  };

  // 错误处理函数
  const handleApiError = (error) => {
    console.error("API Error:", error);
    const errorMessage = {
      400: "忙碌中，请重试",
      401: "未授权，请登录后重试",
      404: "忙碌中，请重试",
      500: "忙碌中，请重试",
    }[error.response?.status] || "请登录后重试";
    message.error(errorMessage);
  };

  // 使用Effect钩子处理副作用
  useEffect(() => {
    const fetchData = async () => {
      if (activeKey === "init" || activeKey === "AddConversation") {
        try {
          const conversations = await fetchApi('/conversations');
          const formattedConversations = (conversations.data || []).map(conversation => ({
            key: conversation.conversation_id,
            label: conversation.title,
          }));
          setConversationsItems(formattedConversations);
          if (formattedConversations.length > 0 && activeKey === "AddConversation") {
            setActiveKey(formattedConversations[0].key);
            setConversationId(formattedConversations[0].key);
          } else if (formattedConversations.length === 0) {
            setConversationsItems([]);
            setActiveKey(null);
            setConversationId(null);
          }
        } catch (error) {
          console.error('Error fetching conversations:', error);
        }
      } 
    };

    fetchData();
  }, [activeKey]);

  // 请求聊天
  const fetchRequest = XRequest({
    baseURL: `${BASE_URL}${PATH}/chat`,
    fetch: (url, options) => {
      const controller = new AbortController();
      const signal = controller.signal;
      const timeoutId = setTimeout(() => controller.abort(), 300000); // 超时5分钟

      abortRef.current = () => controller.abort();

      return fetch(url, {
        method: "POST",
        body: options.body,
        headers: { Authorization: `Bearer ${getToken()}` },
        signal,
      })
        .then((response) => {
          clearTimeout(timeoutId);
          return response;
        })
        // .catch((error) => {
        //   console.error("Fetch error:", error);
        // });
    },
  });


  // 请求聊天的异步函数
  const requestChat = async (question) => {
    const userMessage = { id: uuidv4(), message: question, role: "user" };
    const assistantMessage = { id: uuidv4(), message: "等待中...", role: "assistant" };

    setMessages((prev) => [...prev, userMessage, assistantMessage]);
    setHistoryMessages(prevHistory => [
      ...prevHistory,
      { id: userMessage.id,role: "user", content: question },
      
    ]);

    setLoading(true);
    let AddConversation_flag = false;
    let newContent = '';
    try {
      await fetchRequest.create(
        {
          message: question,
          history: historyMessages,
          stream: true,
          model: selectedModel,
          conversation_id: conversationId,
        },
        {
          onUpdate: (response) => {
            if (conversationId === null && !AddConversation_flag) { // 检查标志变量
              setActiveKey("AddConversation");
              AddConversation_flag = true;
            }
            const data = JSON.parse(response.data);
            if (data.data[0].choices[0].delta.content) {
              newContent += data.data[0].choices[0].delta.content;
              setMessages(prevMessages =>
                prevMessages.map(msg =>
                  msg.id === assistantMessage.id
                    ? { ...msg, message:  RenderMarkdown(newContent) }
                    : msg
                )
              );

              setHistoryMessages(prevHistory =>{
                // 检查是否已经存在 assistantMessage.id 的消息
                const assistantMessageExists = prevHistory.some(msg => msg.id === assistantMessage.id);

                if (assistantMessageExists) {
                  // 如果存在，更新现有消息的内容
                  return prevHistory.map(msg =>
                    msg.id === assistantMessage.id
                      ? { ...msg, content: newContent }
                      : msg
                  );
                } else {
                  // 如果不存在，添加新的消息对象
                  return [...prevHistory, { id: assistantMessage.id, role: "assistant", content: newContent }];
                }
              });
            }
          },
          onSuccess: () => {
            setLoading(false);
          },
        }
      );
    } catch (error) {
      if (error.name === 'AbortError') {
        setMessages(prevMessages =>
          prevMessages.map(msg =>
            msg.id === assistantMessage.id
              ? { ...msg, message:  RenderMarkdown(newContent + "\n\n **_本次回答已被终止_**") }
              : msg
          )
        );
      } else {
        console.error("请求有错误！", error);
        handleApiError(error);
        setLoading(false);

        handleApiError(error);
        // setMessages(prevMessages =>
        //   prevMessages.map(msg =>
        //     msg.id === assistantMessage.id
        //       ? { ...msg, message: <ContentRenderer content="忙碌中，请登录重试" /> }
        //       : msg
        //   )
        // );
      };
    }
  };

  const onSubmit = (nextContent) => {
    if (!nextContent) return;
    requestChat(nextContent);
    setContent('');  //清空输入框
    setLoading(true); // 显示发送按钮 loading 状态
  };

  const onCancel = () => {
    if (abortRef.current) abortRef.current();
    setLoading(false);
  };

  const handlePromptsItemClick = (info) => {
    onSubmit(info.data.description);
    setHistoryMessages([]); // 清空历史消息
    setContent(''); //清空输入框
  };

  const getMessage = async (conversationId) => {
    try {
      const conversationDetails = await fetchApi(`/conversations/${conversationId}`);
      const formattedMessages = conversationDetails.data?.map(msg => ({
        id: msg.message_id,
        message: <ContentRenderer content={msg.content} getContent={ false } />,
        role: msg.sender_type,
      })) || [];
      setMessages(formattedMessages);
    } catch (error) {
      console.error('Error fetching conversation details:', error);
      // 可以添加更多的错误处理逻辑，例如显示错误信息给用户或重试机制
    }
  }
  
  const onConversationClick = (key) => {
    if (loading || key === conversationId) return;
    
    setActiveKey(key);
    setConversationId(key);
    setHistoryMessages([]); // 清空历史消息
    getMessage(key);
  }

  const onAddConversation = () => {
    if (messages.length !== 0 && loading === false) {
      setMessages([]); // 清空当前消息
      setHistoryMessages([]); // 清空当前历史消息
      setConversationId(null); // 清空当前会话ID
      setActiveKey(null); // 清空当前激活会话ID
    } 
    else if (loading === true) {
    }
    else {
      message.info("已是最新会话");
    }
  };



  const placeholderNode = (
    <div>
      <Space direction="vertical" size={16} className={styles.placeholder}>
        <WelcomeMessage />
        <TipsPrompts onPromptsItemClick={handlePromptsItemClick} />
      </Space>
    </div>
  );

  return (
    <div className={styles.layout}>
      <div className={styles.menu}>
        <ConversationsManger
          onAddConversation={onAddConversation}
          onConversationClick={onConversationClick}
          conversationsItems={conversationsItems}
          activeKey={activeKey}
        />
      </div>
      <div className={styles.chat}>
        <BubbleChat
          items={messagesItems}
          placeholderNode={placeholderNode}
          RenderMarkdown={RenderMarkdown}
        />
        <AttachmentInput
          styles={styles}
          onSubmit={onSubmit}
          content={content}
          setContent={setContent}
          loading={loading}
          setLoading={setLoading}
          onCancel={onCancel}
        />
      </div>
    </div>
  );
};

export default DefaultLayout;